package com.yupi.yupicturebackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import com.yupi.yupicturebackend.exception.ThrowUtils;
import com.yupi.yupicturebackend.manager.CosManager;
import com.yupi.yupicturebackend.manager.FileManager;
import com.yupi.yupicturebackend.manager.upload.FilePictureUpolad;

import com.yupi.yupicturebackend.manager.upload.PictureUploadTemp;
import com.yupi.yupicturebackend.manager.upload.UrlPictureUpload;
import com.yupi.yupicturebackend.model.dto.file.UploadPictureResult;
import com.yupi.yupicturebackend.model.dto.picture.*;
import com.yupi.yupicturebackend.model.entity.Picture;
import com.yupi.yupicturebackend.model.entity.Space;
import com.yupi.yupicturebackend.model.entity.User;
import com.yupi.yupicturebackend.model.enums.PictureReviewStatusEnum;
import com.yupi.yupicturebackend.model.vo.PictureVO;
import com.yupi.yupicturebackend.model.vo.UserVO;
import com.yupi.yupicturebackend.service.PictureService;
import com.yupi.yupicturebackend.mapper.PictureMapper;
import com.yupi.yupicturebackend.service.SpaceService;
import com.yupi.yupicturebackend.service.UserService;
import com.yupi.yupicturebackend.util.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.jsoup.nodes.Document;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Y9000
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-09-17 13:54:43
*/
@Slf4j
@Service
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture> implements PictureService{


    @Resource
    private FileManager fileManager;

//    @Resource
//    private PictureUploadTemp pictureUploadTemp;


    @Resource
    private TransactionTemplate transactionTemplate;


    @Resource
    private SpaceService spaceService;


    @Resource
    private UserService userService;

    @Resource
    private FilePictureUpolad filePictureUpolad;

    @Resource
    private UrlPictureUpload urlPictureload;
    @Autowired
    private CosManager cosManager;


    @Override
    public void checkSpaceAuth(User loginUser, Picture space) {
        // 仅本人或管理员可编辑
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

    //上传图片
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) throws IOException {

        //校验参数
        ThrowUtils.throwIf(loginUser==null, ErrorCode.NOT_LOGIN_ERROR);
        //判断是新增还是删除
        Long pictureId=null;
        if(pictureUploadRequest!=null){
            pictureId=pictureUploadRequest.getId();
        }

        //校验空间是否存在
        Long spaceId=pictureUploadRequest.getSpaceId();
        if(spaceId!=null){
            Space space=spaceService.getById(spaceId);
            ThrowUtils.throwIf(space==null,ErrorCode.NOT_FOUND_ERROR);
            //校验是否有空间权限，仅空间管理员才能上传
            if(!loginUser.getId().equals(space.getUserId())){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有空间权限");
            }

            //校验额度
            if(space.getTotalSize()>=space.getMaxSize()){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"空间条数不足");
            }
            if(space.getTotalCount()>=space.getMaxCount()){
                throw new BusinessException(ErrorCode.OPERATION_ERROR,"空间大小不足");
            }

        }

        //如果是更新，判断图片是否存在
        if(pictureId!=null){
            Picture oldPicture = this.getById(pictureId);
            ThrowUtils.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR,"aaa");
            //仅本人或管理员可以编辑
            if(!oldPicture.getUserId().equals(loginUser.getId())&&!userService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }

            //校验空间是否一致
            //没传spaceId,则复用原有图片的spaceId
            if(spaceId==null){
                if(oldPicture.getSpaceId()!=null){
                    spaceId=oldPicture.getSpaceId();
                }else{
                    if(ObjUtil.notEqual(spaceId,oldPicture.getSpaceId())){
                        throw new BusinessException(ErrorCode.OPERATION_ERROR,"空间不一致");
                    }
                }
            }
        }
        //上传图片，得到图片信息
        //按照用户id 划分目录
        String uploadPathPrefix= String.format("public/%s `",loginUser.getId());
        //根据inpustSource类型区分上传方式
        PictureUploadTemp pictureUploadTemp = filePictureUpolad;
        if(inputSource instanceof String){
            pictureUploadTemp = urlPictureload;
        }

        UploadPictureResult uploadPictureResult = pictureUploadTemp.uploadPicture(inputSource, uploadPathPrefix);
        //构造要入库的图片信息
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setName(uploadPictureResult.getPicName());
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        String piName= uploadPictureResult.getPicName();
        if(pictureUploadRequest!=null &&StrUtil.isNotBlank(pictureUploadRequest.getPicName())){
            piName=pictureUploadRequest.getPicName();
        }
        picture.setName(piName);

        //补充审核参数
        fillReviewParams(picture,loginUser);


        //操作数据库
        if(pictureId==null){
            //如果是更新，需要补充id和编辑时间
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }

        //开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean result=this.saveOrUpdate( picture);
            ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR,"保存图片失败");
            if(finalSpaceId!=null){
            boolean update= spaceService.lambdaUpdate()
                        .eq(Space::getId,finalSpaceId)
                        .setSql("totalSize=totalSize+",picture.getPicSize())
                        .setSql("totalCount=totalCount+1")
                        .update();
                ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR,"更新空间失败");

            }
            return picture;
        });

        boolean saveResult = this.saveOrUpdate(picture);

        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR,"保存图片失败");

        return PictureVO.objToVo(picture);
    }

    @Override
    public void deletePicture(Long pictureId, User loginUser) {
        ThrowUtils.throwIf(pictureId <= 0, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        // 判断是否存在
        Picture oldPicture = this.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 校验权限，已经改为使用注解鉴权
//        checkPictureAuth(loginUser, oldPicture);
        // 开启事务
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(pictureId);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

            // 只有当图片关联了空间时才更新空间的使用额度
            if (oldPicture.getSpaceId() != null) {
                // 更新空间的使用额度，释放额度
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, oldPicture.getSpaceId())
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return true;
        });
        // 异步清理文件
        this.clearPictureFile(oldPicture);
    }

    // 获取查询条件
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {

        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Long spaceId = pictureQueryRequest.getSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            // and (name like "%xxx%" or introduction like "%xxx%")
            queryWrapper.and(
                    qw -> qw.like("name", searchText)
                            .or()
                            .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "spaceId");
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);
        // >= startEditTime
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime), "editTime", startEditTime);
        // < endEditTime
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime), "editTime", endEditTime);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            /* and (tag like "%\"Java\"%" and like "%\"Python\"%") */
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;



    }


    //     *获取图片包装类（单条）
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {

        // 对象转封装类
        PictureVO pictureVO= PictureVO.objToVo(picture);

        //关联查询用户信息
        Long userId = picture.getUserId();
        if(userId != null && userId > 0){
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }

        return pictureVO;



    }

    //     *获取图片包装类（多条）
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {

        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVOPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());
        if (CollUtil.isEmpty(pictureList)) {
            return pictureVOPage;
        }
        //对象列表=》  封装列表
        List<PictureVO> pictureVOList = pictureList.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
        //关联查询用户信息
        //
        Set<Long> userIdSet = pictureVOList.stream().map(PictureVO::getUserId).collect(Collectors.toSet());
        //1=>user1 2.=>user2
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));

        //2.填充用户信息
        pictureVOList.forEach(pictureVO -> {
            Long userId = pictureVO.getUserId();
            User user =null;

            if (userIdUserListMap.containsKey(userId)){
                user = userIdUserListMap.get(userId).get(0);
            }

            pictureVO.setUser(userService.getUserVO(user));
        });
        pictureVOPage.setRecords(pictureVOList);

        return pictureVOPage;
    }


    //图片审核仅限管理员
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {


        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 判断是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR);
        //已是该状态
        if(oldPicture.getReviewStatus().equals(reviewStatus)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"图片已审核");
        }

        //更新审核状态
        Picture updatePicture = new Picture();
        BeanUtil.copyProperties(pictureReviewRequest,updatePicture);
        updatePicture.setReviewStatus(reviewStatus);
        updatePicture.setReviewTime(new Date());
        boolean result=this.updateById(updatePicture);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);

    }

    //图片编辑
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {

        //判断是否存在
        Long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture==null,ErrorCode.NOT_FOUND_ERROR);

        //在此处进行实体类和DTO类进行转换
        Picture picture = new Picture();
        BeanUtil.copyProperties(pictureEditRequest,picture);
        //注意将list转为string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        //设置编辑时间
        picture.setEditTime(new Date());
        //数据校验
        this.validPicture(picture);

        //补充审核参数
        this.fillReviewParams(picture,loginUser);
        //操作数据库
        boolean result=this.updateById(picture);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR);

    }

    //补充审核参数 审核照片参数设置
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (userService.isAdmin(loginUser)) {


            // 管理员自动过审
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewerId(loginUser.getId());
            picture.setReviewMessage("管理员自动过审");
            picture.setReviewTime(new Date());

        } else {
            // 非管理员，无论是编辑还是创建默认都是待审核
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
        }
    }


    //图片上传(批量）
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {

        String searchText = pictureUploadByBatchRequest.getSearchText();
        //格式化数量
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count <= 0 || count > 100, ErrorCode.PARAMS_ERROR, "数量不能小于0或者大于100");

        //要抓取的地址
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);
        Document document;

        try {
            document=  Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("Jsoup.connect(fetchUrl).get() error", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片抓取失败");
        }
        Element  div=document.getElementsByClass("dgControl").first();
        if(ObjUtil.isNull( div)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "图片抓取失败");
        }

        Elements imgElementList= document.select("img.mimg");
        int uploadCount = 0;
        for (Element element : imgElementList) {
            String fileUrl=element.attr("src");
            if(StrUtil.isBlank(fileUrl)){
            log.info("图片地址为空{}", fileUrl);
            continue;
            }
            //处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }

            String namePrefix= pictureUploadByBatchRequest.getNamePrefix();
            if(StrUtil.isBlank(namePrefix)){
                namePrefix=searchText;
            }

            //上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();


            if(StrUtil.isNotBlank(namePrefix)){

                pictureUploadRequest.setPicName(namePrefix+(uploadCount+1));
            }

            try {
                PictureVO pictureVO=this.uploadPicture(fileUrl,pictureUploadRequest,loginUser);
                log.info("图片上传成功{}", pictureVO.getId());
                uploadCount++;
            } catch (IOException e) {
                log.error("图片上传失败{}", e.getMessage());
                continue;
            }
            if(uploadCount>=count){
                break;
            }

        }

        return uploadCount;
    }


    //删除cel
    @Async
    @Override
    public void clearPictureFile(Picture oldPicture) {
        if (oldPicture == null) {
            return;
        }

        //判断该图片是否被多条记录使用
        String picturUrl=oldPicture.getUrl();
        Long count = this.count(new QueryWrapper<Picture>().eq("url", picturUrl));
        if (count > 1) {
            return;
        }
        //FIXME 注意，这里的url包含了域名， 实际上只要传key值就够了
        cosManager.deleteObject(oldPicture.getUrl());

        //清理缩略图
        String thumbnailUrl=oldPicture.getThumbnailUrl();
        if(StrUtil.isNotBlank(thumbnailUrl)){
            cosManager.deleteObject(thumbnailUrl);
        }
    }


    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        // 如果传递了 url，才校验
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    //根据颜色搜索图片
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser){
        //校验参数
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(StrUtil.isBlank(picColor), ErrorCode.PARAMS_ERROR);
        //校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        if(!loginUser.getId().equals(space.getUserId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有空间访问权限");
        }
        //查询该空间下所有图片
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();

        //如果没有图片则直接返回列表

        if(pictureList.isEmpty()){
            return new ArrayList<>();
        }
        //将目标转为Color对象
        Color targetColor = Color.decode(picColor);
        //计算相似度并排序

        List< Picture>sortedPicture= pictureList.stream()
                .sorted(Comparator.comparingDouble(picture->{
                    //提取图片主色调
                    String hexColor = picture.getPicColor();
                    //没有主色调的图片放到最后
                    if(StrUtil.isBlank(hexColor)){
                        return Double.MAX_VALUE;
                    }
                    Color color = Color.decode(hexColor);
                    //    //越大越相似
                    return ColorSimilarUtils.calculateSimilarity(targetColor, color);
                }))
                .limit(12)
                .collect(Collectors.toList());



        //转换为PictureVO

        return sortedPicture.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());

    }

    //批量编辑图片
    @Override
    public boolean editPictureBatch(PictureEditByBatchRequest pictureEditBatchRequest, User loginUser) {

        List< Long>pictureIdList=pictureEditBatchRequest.getPictureIdList();
        Long spaceId=pictureEditBatchRequest.getSpaceId();
        String category=pictureEditBatchRequest.getCategory();
        List<String> tags=pictureEditBatchRequest.getTags();

        //1.校验参数
        ThrowUtils.throwIf(pictureIdList==null||pictureIdList.isEmpty(),ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(spaceId==null,ErrorCode.PARAMS_ERROR);
        //校验空间
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space==null,ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        if(!loginUser.getId().equals(space.getUserId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有空间访问权限");
        }

        //查询指定图片 选择需要的字段
        List<Picture>pictureList=this.lambdaQuery()
                .select(Picture::getId,Picture::getSpaceId)
                .eq(Picture::getSpaceId,spaceId)
                .in(Picture::getId,pictureIdList)
                .list();

        if(pictureList.isEmpty()){
            return false;
        }

        String name=pictureEditBatchRequest.getNameRule();
        fillPictureWithNameRule(pictureList,name);


        //更新分类和标签
        pictureList.forEach(picture->{
            if(StrUtil.isNotBlank( category)){
                picture.setCategory(category);
            }
            if((CollUtil.isNotEmpty( tags))){
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
        });

        //批量更新
        boolean update = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!update,ErrorCode.SYSTEM_ERROR);
        return update;
    }

    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (StrUtil.isBlank(nameRule) || CollUtil.isEmpty(pictureList)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }
}




